/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.site.client.editor;

import java.util.HashMap;
import java.util.List;

import nl.biz_e.gwt.baselib.ui.client.widgets.DateField;
import nl.biz_e.gwtappengine.lib.client.rpc.BaseAsyncCallback;
import nl.biz_e.site.client.NewsService;
import nl.biz_e.site.client.NewsServiceAsync;
import nl.biz_e.site.shared.models.NewsItem;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Joost A. Bloemsma
 * 
 */
public class NewsEditPanel extends EditorPanelBase {
	
	private final NewsServiceAsync newsService;
	private ListBox itemList = null;
	private final DateField date;
	private final TextBox title;
	private final TextBox descr;
	private final TextArea editor;
	private final Button saveBtn;
	private final Button newBtn;
	private final HashMap<String, NewsItem> items = new HashMap<String, NewsItem>();
	private NewsItem currentItem = null;
	
	/**
	 * Constructs a new NewsEditPanel instance
	 */
	public NewsEditPanel() {
		super();
		int row = 0;
		newsService = GWT.create(NewsService.class);
		Grid grid = new Grid(6, 2);
		grid.setWidth("100%");
		grid.setWidget(row, 0, getLabel(strings.newsitem()));
		HorizontalPanel hp = new HorizontalPanel();
		newBtn = new Button(strings.newlbl(), this);
		hp.add(getItemList());
		hp.add(newBtn);
		grid.setWidget(row, 1, hp);
		row++;
		
		grid.setWidget(row, 0, getLabel(strings.date()));
		date = new DateField();
		grid.setWidget(row, 1, date);
		row++;
		
		grid.setWidget(row, 0, getLabel(strings.title()));
		title = new TextBox();
		grid.setWidget(row, 1, title);
		row++;
		
		grid.setWidget(row, 0, getLabel(strings.title()));
		descr = new TextBox();
		grid.setWidget(row, 1, descr);
		row++;
		
		grid.setWidget(row, 0, getLabel(strings.text()));
		editor = new TextArea();
		editor.setWidth("100%");
		editor.setHeight("100px");
		grid.setWidget(row, 1, editor);
		row++;
		
		grid.setWidget(row, 0, getLabel(""));
		saveBtn = new Button(strings.save(), this);
		grid.setWidget(row, 1, saveBtn);
		this.add(grid);
	}
	
	private Widget getLabel(String txt) {
		if (txt.length() > 0)
			txt += ": ";
		return new InlineLabel(txt);
	}
	
	private ListBox getItemList() {
		if (itemList == null) {
			itemList = new ListBox();
			itemList.addChangeHandler(this);
			refreshItemList();
		}
		return itemList;
	}
	
	private void refreshItemList() {
		itemList.clear();
		itemList.addItem(strings.select(), "");
		newsService.getAll(new BaseAsyncCallback<List<NewsItem>>() {
			@Override
			public void onSuccess(List<NewsItem> result) {
				for (NewsItem item : result) {
					String id = item.getSeqNr() + ": " + item.getTitle();
					items.put(id, item);
					itemList.addItem(id);
				}
				
			}
		});
	}
	
	private void selectionChanged() {
		String id = itemList.getItemText(itemList.getSelectedIndex());
		NewsItem item = this.items.get(id);
		this.setNewsItem(item);
		return;
	}
	
	private void setNewsItem(final NewsItem item) {
		if (item == null) {
			setNewsItem(new NewsItem());
			return;
		}
		if (item.getSeqNr() > 0) {
			newsService.getFullText(item, new BaseAsyncCallback<String>() {
				@Override
				public void onSuccess(String result) {
					setNewsItem(item, result);
				}
			});
		} else {
			setNewsItem(item, "");
		}
	}
	
	private void setNewsItem(NewsItem item, String fullText) {
		if (item.getSeqNr() > 0) {
			String id = item.getSeqNr() + ": " + item.getTitle();
			for (int i = 0; i < itemList.getItemCount(); i++) {
				if (itemList.getItemText(i).equals(id)) {
					itemList.setSelectedIndex(i);
					i = itemList.getItemCount();
				}
			}
		} else {
			itemList.setSelectedIndex(0);
		}
		
		date.setValue(item.getDate());
		title.setValue(item.getTitle());
		descr.setValue(item.getText());
		editor.setValue(fullText);
		this.currentItem = item;
	}
	
	private void createNew() {
		setNewsItem(new NewsItem());
	}
	
	private void doSave() {
		String fulltext = editor.getValue();
		
		if (currentItem == null) {
			currentItem = new NewsItem();
		}
		
		currentItem.setDate(this.date.getValue());
		currentItem.setTitle(title.getValue());
		currentItem.setText(descr.getValue());
		
		newsService.saveNewsItem(currentItem, fulltext, new BaseAsyncCallback<NewsItem>() {
			@Override
			public void onSuccess(NewsItem result) {
				currentItem = result;
				refreshItemList();
				setNewsItem(currentItem);
			}
		});;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onChange(ChangeEvent event) {
		if (event.getSource() == itemList) {
			selectionChanged();
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onClick(ClickEvent event) {
		if (event.getSource() == saveBtn) {
			doSave();
		}
		if (event.getSource() == newBtn) {
			createNew();
		}
	}
	
}
